from fastapi import APIRouter, Body, Request, File, UploadFile, HTTPException
from sqlalchemy.orm import Session
from models import ResponseModel, ResponseList
from schemas.nurse_schema import MedicalCaseCreate, ListMedicalCase, ItemMedicalCase,MedicalCaseUpdate
from curd.nurse_curd import create_medical_case, get_medical_cases, get_medical_case, del_medical_case, update_medical_case
from db import Db

# 创建一个 APIRouter 实例
medical = APIRouter(
	prefix='/medical',
	tags=['medical 护理病例模块']
)

@medical.post('/create',summary="新增护理")
async def add_medical_case(
  request: Request,
  case: MedicalCaseCreate = Body(..., description="新增病例信息"),
  db: Session = Db
):
  res = create_medical_case(db=db, case=case)
  if res:
   # 将SQLAlchemy模型转换为Pydantic模型
    item = ItemMedicalCase.from_orm(res)
    print("db_case3",item)
    return ResponseModel.success(data=item)
  else:
    return ResponseModel.error(code=401, message="新增失败")


@medical.post('/get-list', summary="查询病例列表")
def list_medical_case(case: ListMedicalCase, db: Session = Db):
  db_data = get_medical_cases(db=db, case=case)
  if db_data:
    return ResponseList.success(data=db_data)
  else:
    return ResponseList.error(code=404, message="没有数据")


@medical.get('/get-case/{case_id}', summary="获取病例详情")
def get_medical_case_detail(case_id: int, db: Session = Db):
  db_data = get_medical_case(db=db, id=case_id)
  if db_data:
    # 将SQLAlchemy模型转换为Pydantic模型
    item = ItemMedicalCase.from_orm(db_data)
    return ResponseModel.success(data=item)
  else:
    return ResponseModel.error(code=404, message="病例不存在")


@medical.post('/update', summary="更新病例")
def patch_medical_case(
  case: MedicalCaseUpdate = Body(..., description="更新数据"),
  db: Session = Db
):
  try:
      item_data = update_medical_case(db=db, case=case)
      return ResponseModel.success(data=item_data)
  except HTTPException as e:
      return ResponseModel.error(code=e.status_code, message=e.detail)
  except Exception as e:
      return ResponseModel.error(code=500, message="服务器内部错误")


@medical.delete('/delete/{case_id}', summary="删除病例")
def delete_medical_case(case_id: int, db: Session = Db):
  result = del_medical_case(db=db, id=case_id)
  return ResponseModel.success(data=result)

